import { saveRecordInitAssignAccount } from '@/services/api/api-interview-record';
import ProForm, { DrawerForm, ProFormInstance, ProFormSelect } from '@ant-design/pro-form';
import { Spin } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import React, { useState } from 'react';

interface AssignAccountProps {
  formRef: ProFormInstance | undefined;
  visibleAssign: boolean;
  assignsAccounts: UserData.OrganizationOption[];
  onSave: () => void;
  setVisibleReadReauest: () => void;
  setaccountsLenght: () => void;
}

const AssignAccount: React.FC<AssignAccountProps> = ({
  formRef,
  visibleAssign,
  assignsAccounts,
  onSave,
  setVisibleReadReauest,
  setaccountsLenght,
}) => {
  const [loading, setLoading] = useState(false);

  const [dataTreeAccount, setDataTreeAccountState] = useState<DataNode[]>();
  const [dataCheckTreeAccount, setDataCheckTreeAccountState] = useState<any>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeAccountData(data: Array<UserData.Organization>): DataNode[] {
    const treeData = new Array();

    if (data) {
      data.forEach((val, idx, array) => {
        treeData.push({
          title: val.name,
          key: val.id,
          children: readyTreeAccountData(val.children as Array<UserData.Organization>),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载组织树请求网络
   */
  const loadAccountTreeAccountData = async () => {
    try {
      setLoading(true);
      const response = await saveRecordInitAssignAccount();
      if (response.code === 0) {
        setDataTreeAccountState(readyTreeAccountData(response.data));
      }
      setLoading(false);
    } catch (error) {}
  };

  return (
    <ProForm.Group
      style={{
        display: visibleAssign ? 'block' : 'none',
      }}
    >
      <ProFormSelect
        name="assignAccounts"
        label="已选"
        width="xl"
        style={{
          width: '850px',
        }}
        showSearch
        hidden={!visibleAssign}
        fieldProps={{
          mode: 'multiple',
          allowClear: true,
          showSearch: true,
          open: false,
          optionFilterProp: 'children',
          filterOption: (input: any, option: any) => {
            if (option.label) {
              return option.label.includes(input);
            }
          },
          listHeight: 500,
          style: {
            marginLeft: '28px',
          },
        }}
        onChange={(value) => {
          console.log(value);
          setaccountsLenght(value.length);
          if (value?.length === 0) {
            onSave(false);
            formRef?.current?.setFieldsValue({
              completeType: '1',
            });
            setVisibleReadReauest(false);
          }
        }}
        rules={[{ required: visibleAssign, message: '请选择至少一个联络人' }]}
        options={assignsAccounts}
        addonAfter={
          <DrawerForm
            width="500px"
            title="报送范围：联络人（多选）"
            trigger={
              <a key="activeSaveAssign" onClick={() => {}}>
                点击添加
              </a>
            }
            autoFocusFirstInput
            drawerProps={{
              destroyOnClose: true,
            }}
            onOpenChange={(visible: boolean) => {
              if (visible) {
                loadAccountTreeAccountData();
                setDataCheckTreeAccountState(formRef?.current?.getFieldValue('assignAccounts'));
              }
              formRef?.current?.setFieldsValue({
                countRead: formRef?.current?.getFieldValue('assignAccounts')?.length,
              });
            }}
            submitter={false}
            onFinish={async (values) => {}}
          >
            <Spin spinning={loading}>
              {dataTreeAccount && dataTreeAccount.length ? (
                <Tree
                  treeData={dataTreeAccount}
                  checkedKeys={dataCheckTreeAccount}
                  checkable
                  onCheck={(checkedKeys, e) => {

                    const checkKeys = new Array();
                    e.checkedNodesPositions?.forEach((item) => {
                      if (item.node.children?.length === 0) {
                        checkKeys.push(item.node.key);
                      }
                    });
                    
                    setDataCheckTreeAccountState(checkedKeys);
                    console.log(checkKeys);
                    if (checkKeys.length > 0) {
                      onSave(true);
                    } else {
                      onSave(false);
                    }
                    setaccountsLenght(checkKeys.length);
                    formRef?.current?.setFieldsValue({
                      assignAccounts: checkKeys,
                    });
                  }}
                />
              ) : (
                '暂无数据'
              )}
            </Spin>
          </DrawerForm>
        }
      />
    </ProForm.Group>
  );
};

export default AssignAccount;
